package org.example.blog_manage.Controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.blog_manage.constants.Constants;
import org.example.blog_manage.model.CaptchaInfo;
import org.example.blog_manage.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@Slf4j
@RequestMapping("/Captcha")
@RestController
public class CaptchaController {

    private static final long setTime = 60*1000;

    @Autowired
    private CaptchaInfo captchaInfo;


    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaInfo.getWidth(), captchaInfo.getHeight(), captchaInfo.getCodeCount(), captchaInfo.getCircleCount());
        //设置响应类型
        response.setContentType("image/png");
        response.setHeader("Pragma","No-cache");
        captcha.write(response.getOutputStream());
        String code = captcha.getCode();
//        存储在Session中，由于判断
//        放入常量类中
        session.setAttribute(Constants.SESSION_KEY,code);
        session.setAttribute(Constants.SESSION_TIME,new Date());

        //关闭流
        response.getOutputStream().close();

    }

    @RequestMapping("check")
    public Result check(String inCode, HttpSession session) {
        if (!StringUtils.hasLength(inCode)) {
            return Result.Fail("输入为空");
        }

        // 获取session中的验证码和时间
        String captchaKey = (String) session.getAttribute(Constants.SESSION_KEY);
        Date captchaTime = (Date) session.getAttribute(Constants.SESSION_TIME);

        // 检查session中是否存在验证码
        if (captchaKey == null || captchaTime == null) {
            return Result.Fail("验证码已失效，请刷新");
        }

        long nowTime = System.currentTimeMillis();
        long timeDiff = nowTime - captchaTime.getTime();

        // 先检查验证码是否正确
        if (captchaKey.equalsIgnoreCase(inCode)) {
            // 再检查是否过期
            if (timeDiff < setTime) {
                // 验证通过后立即清除session中的验证码（防止重复使用）
                session.removeAttribute(Constants.SESSION_KEY);
                session.removeAttribute(Constants.SESSION_TIME);
                return Result.success("验证码正确");
            } else {
                return Result.Fail("验证码已过期");
            }
        }
        return Result.Fail("验证码有误");
    }

}
